package com.StarStudio.Controller;

import cn.hutool.core.util.IdUtil;
import com.StarStudio.Service.BeansActionService;
import com.StarStudio.Service.RateService;
import com.StarStudio.Service.UserInfoService;
import com.StarStudio.Utils.QueryPageUtils;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user_info")
@Api(tags = "用户信息接口")
public class UserInfoController {

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    RateService rateService;

    @Autowired
    BeansActionService beansActionService;

    /**
     * 条件查询 用户信息分页接口
     * @param userInfo 用户信息对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page")
    @ApiOperation("商城用户信息分页接口 -> 支持条件检索，检索条件封装在用户对象UserInfo中。如需分页，必传pageNum和pageSize")
    public PageResult page(UserInfo userInfo){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<UserInfo> userInfoList;
        long allRecordNumber;
        try {
            userInfoList = userInfoService.findUserInfoList(userInfo);
            allRecordNumber = userInfoService.findAllRecordNumber();
            pageInfo = new PageInfo<>(userInfoList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS,pageInfo.getTotal(), userInfoList, allRecordNumber);
    }

    /**
     * 将通过登录校验的用户信息保存到数据库
     * 如果第一次登录，保存用户所有信息，如果不是第一次登录，更新用户信息（这些信息从省平台获取）
     * @param userInfo 用户信息对象
     * @return 结果对象 Result
     */
    @PostMapping
    @SuppressWarnings("deprecation")
    @ApiOperation("将通过登录校验的用户信息保存到数据库 -> 如果第一次登录，保存用户所有信息，如果不是第一次登录，更新用户信息（这些信息从省平台获取）" +
            "其中：用户ID、用户真实姓名、身份证号、卡类型、社保卡号、头像图片URL地址、手机号、志愿服务时长、星级等信息不可为空")
    public Result UserInfoSave(@RequestBody UserInfo userInfo){
        if (userInfo.getId() == null || userInfo.getCard_num() == null || userInfo.getCard_type() == null || userInfo.getIcbc_card_num() == null
            || userInfo.getAvatar() == null || userInfo.getMobile() == null || userInfo.getHours() == null || userInfo.getStar() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        String mobile = null;
        int beans;
        try {
            //获取当前志愿者服务时长和鲜豆积分的兑换率
            Rate currentRate = rateService.findCurrentRate();
            String encodeMobile = userInfo.getMobile();
            if (!StringUtils.isEmpty(encodeMobile)){
                //解密手机号
                //mobile = DESedeUtils.decrypt(encodeMobile, HttpRequestUtils.getProvinceSystemToken());
                //不需解密
                mobile = encodeMobile;
            }
            int byCondition = userInfoService.findByCondition(userInfo); //查询商城平台数据库是否有相关信息
            if (byCondition != 0){
                /* 用户非首次登录 */
                UserInfo byUserId = userInfoService.findByUserId(userInfo.getId());//从我们平台的数据库中获取已存在的用户信息
                // 给用户对象更新值
                byUserId.setAvatar(userInfo.getAvatar());
                byUserId.setMobile(mobile);
                beans = byUserId.getBeans();
                if (userInfo.getHours() > byUserId.getHours()){ //服务时长增加了，新增鲜豆积分
                    //计算新增的鲜豆  新增小时数乘以当前兑换率
                    byUserId.setBeans(byUserId.getBeans() + BigDecimal.valueOf(currentRate.getRate()).multiply(BigDecimal.valueOf(userInfo.getHours() - byUserId.getHours())).intValue());
                    beans = byUserId.getBeans();
                    //往 BeansAction中更新数据
                    BeansAction beansAction = new BeansAction();
                    beansAction.setBeans_action_describe("志愿服务时长增加" + BigDecimal.valueOf(userInfo.getHours() - byUserId.getHours()).doubleValue() + "小时");
                    beansAction.setBeans_action_number(BigDecimal.valueOf(currentRate.getRate()).multiply(BigDecimal.valueOf(userInfo.getHours() - byUserId.getHours())).intValue());
                    beansAction.setBeans_action_type(MessageConstant.BEANS_INCOME);
                    beansAction.setBeans_action_time(new Timestamp(new Date().getTime()));
                    beansAction.setBeans_action_user_id(userInfo.getId());
                    beansAction.setBeans_action_id(IdUtil.getSnowflakeNextId());//使用雪花ID
                    beansActionService.addBeansAction(beansAction);
                }
                byUserId.setHours(userInfo.getHours());
                byUserId.setStar(userInfo.getStar());
                byUserId.setLast_login_time(new Timestamp(new Date().getTime()));
                userInfoService.updateUserInfo(byUserId);
            }else {
                /* 用户首次登录 */
                userInfo.setMobile(mobile);
                //由当前汇率计算鲜豆积分
                beans = BigDecimal.valueOf(currentRate.getRate()).multiply(BigDecimal.valueOf(userInfo.getHours())).intValue();
                //往 BeansAction中更新数据
                BeansAction beansAction = new BeansAction();
                beansAction.setBeans_action_describe("用户首次登录，志愿服务时长换算" + userInfo.getHours() + "小时");
                beansAction.setBeans_action_number(beans);
                beansAction.setBeans_action_type(MessageConstant.BEANS_INCOME);
                beansAction.setBeans_action_time(new Timestamp(new Date().getTime()));
                beansAction.setBeans_action_user_id(userInfo.getId());
                beansAction.setBeans_action_id(IdUtil.getSnowflakeNextId());//使用雪花ID
                beansActionService.addBeansAction(beansAction);
                userInfo.setBeans(beans);
                userInfoService.UserInfoSave(userInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.USER_INFO_SAVE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.USER_INFO_SAVE_SUCCESS,beans);
    }

    /**
     * 由用户ID获取该用户鲜豆值
     * @param userId 用户ID
     * @return 结果对象
     * @Author ChengLee
     * @Date 2023/05/06
     */
    @GetMapping("/userBeans")
    @ApiOperation("由用户ID获取该用户鲜豆值 -> 用户ID不能为空")
    public Result getUserBeans(Long userId){
        if (userId == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        Integer beans;
        try {
            beans = userInfoService.getUserBeans(userId);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_USER_BEANS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_USER_INFO_SUCCESS,beans);
    }
}
